/**
 * 
 */
package org.gov.vis.data.gui.listener;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;

import javax.swing.JOptionPane;

import org.gov.vis.common.exceptions.InvalidInputException;
import org.gov.vis.data.controller.AICtlr;
import org.gov.vis.data.controller.AICtlrImpl;
import org.gov.vis.data.dto.AIDto;
import org.gov.vis.data.gui.EditAIDialog;
import org.gov.vis.data.gui.ViewAIDialog;
import org.gov.vis.gui.util.ErrorsDisplayJPanel;
import org.gov.vis.main.Main;
import org.gov.vis.master.gui.listener.BaseListener;
import org.gov.vis.util.DBConstants;
import org.gov.vis.util.DU;
import org.gov.vis.util.GuiConstants;
import org.gov.vis.util.Util;

/**
 * @author user
 *
 */
public class EditAIListener implements ActionListener,BaseListener{


	private EditAIDialog editAIDialog;
	private AICtlr aiCtlr = new AICtlrImpl();

	private ErrorsDisplayJPanel errorMsgPanel;
	final private ResourceBundle rb = Util.getResources();
	private AIDto aiDto;

	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */

	public EditAIListener(EditAIDialog aiDialog){

		this.editAIDialog = aiDialog;
	}
	@Override
	public void actionPerformed(ActionEvent actionEvent) {
		try{
			errorMsgPanel = new ErrorsDisplayJPanel(editAIDialog.getjPanel1());
			errorMsgPanel.clearMsgPanel();
			if(actionEvent.getActionCommand().equals(rb.getString("dialog_button_update"))){
				//Method called to either Add or Edit the GopalaMithra details
				addOrEditAI();
			}

			if(actionEvent.getActionCommand().equals(rb.getString("dialog_button_delete"))){
				
				int response = JOptionPane.showConfirmDialog(null, GuiConstants.DELETE_CONFIRM_MSG, "Confirm",
				        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
				    
			    if (response == JOptionPane.YES_OPTION) {
			      // User clicked YES.
			    	deleteAI(actionEvent);
			    	String searchText = editAIDialog.getSearchText();

					// It is basically doing back button functionality. Please, understand the logic and write the comments.
					//Replace double quotes with appropriate Dialog title.
					ViewAIDialog viewAiDialog = new ViewAIDialog(Main.getMainFrame(), "View AI", false);
					for(ActionListener actionListener: viewAiDialog.getSearchBtn().getActionListeners()) { 
						ViewAIListener viewAiList = (ViewAIListener)actionListener;
						viewAiDialog.getCodeTxtBx().setText(searchText);

						viewAiList.actionPerformed(new ActionEvent(viewAiDialog.getSearchBtn(), 1, rb.getString("dialog_button_serach")));
					}
			    	
			    } else if (response == JOptionPane.NO_OPTION || response == JOptionPane.CLOSED_OPTION) {
			      return;
			    }

			}

		}catch(Exception e){
			e.printStackTrace();
		}
	}//end actionPerformed

	/**
	 * Method called to delete the AI Object based on the passed aiId
	 * @param _aiId
	 */
	private void deleteAI(ActionEvent actionEvent){

		Long _aiId = (Long)editAIDialog.getHidnObject();
		try {
			aiCtlr.deleteAI(_aiId);
			JOptionPane.showMessageDialog(editAIDialog, rb.getString(GuiConstants.DATA_DELETEAI_SUCCESS));
			editAIDialog.dispose();

			
		} catch (Exception e) {
			List<String> errorMsgLst = new ArrayList<String>();
			errorMsgLst.add(e.getMessage());
			errorMsgPanel.setErrorMessages(errorMsgLst);


		}

	}//end deleteAI


	/**
	 * Method called to either Add or Edit the AI details
	 */
	private void addOrEditAI(){
		//Method called to set the Field's Labels to default Black color
		clearGUILabelColors(blackColor);

		//Method to set the Screen's data to  the DTO Object
		setGuiDetailsToDto(editAIDialog);
		try{
			//Method called to Add or Edit the AI
			aiCtlr.addOrEditAI(aiDto);
			JOptionPane.showMessageDialog(editAIDialog, rb.getString(GuiConstants.DATA_EDITAI_SUCCESS));
			editAIDialog.dispose();
			
			String searchText = editAIDialog.getSearchText();

			// It is basically doing back button functionality. Please, understand the logic and write the comments.
			//Replace double quotes with appropriate Dialog title.
			ViewAIDialog viewAiDialog = new ViewAIDialog(Main.getMainFrame(), "View AI", false);
			for(ActionListener actionListener: viewAiDialog.getSearchBtn().getActionListeners()) { 
				ViewAIListener viewAiList = (ViewAIListener)actionListener;
				viewAiDialog.getCodeTxtBx().setText(searchText);

				viewAiList.actionPerformed(new ActionEvent(viewAiDialog.getSearchBtn(), 1, rb.getString("dialog_button_serach")));
			}


		}catch(Exception e){
			List<String> errorMsgLst = new ArrayList<String>();
			if(e instanceof InvalidInputException){
				final HashMap<String,String> _exceptions = AICtlr.errorMsgs;
				if (_exceptions != null && !_exceptions.isEmpty()) {
					String errMsg = null;

					if(_exceptions.containsKey(rb.getString("dialog_label_ai_code").toUpperCase())){
						editAIDialog.getLblCode().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_ai_code").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					if(_exceptions.containsKey(rb.getString("dialog_label_bullno").toUpperCase())){
						editAIDialog.getLblBullNo().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_bullno").toUpperCase());
						errorMsgLst.add(errMsg);
					}
					if(_exceptions.containsKey(rb.getString("dialog_label_ai_dtofinsumnaton").toUpperCase())){
						editAIDialog.getLblDOI().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_ai_dtofinsumnaton").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					if(_exceptions.containsKey(rb.getString("dialog_label_ai_breed").toUpperCase())){
						editAIDialog.getLblBreed().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_ai_breed").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					if(_exceptions.containsKey(rb.getString("dialog_label_ai_animal_type").toUpperCase())){
						editAIDialog.getLblAnimalType().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_ai_animal_type").toUpperCase());
						errorMsgLst.add(errMsg);
					}
					if(_exceptions.containsKey(rb.getString("dialog_label_ai_kndofanml").toUpperCase())){
						editAIDialog.getLblKindOfAnimal().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_ai_kndofanml").toUpperCase());
						errorMsgLst.add(errMsg);
					}
					if(_exceptions.containsKey(rb.getString("dialog_label_ai_brthgvn").toUpperCase())){
						editAIDialog.getLblBirthsGiven().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_ai_brthgvn").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					if(_exceptions.containsKey(rb.getString("dialog_label_ai_noai").toUpperCase())){
						editAIDialog.getLblNameOfAI().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_ai_noai").toUpperCase());
						errorMsgLst.add(errMsg);
					}
					if(_exceptions.containsKey(rb.getString("dialog_label_ai_aifee").toUpperCase())){
						editAIDialog.getLblAIFee().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_ai_aifee").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					errorMsgPanel.setErrorMessages(errorMsgLst);
				} else {
					//log.debug(e.getMessage(), e);
				}	
			}
			else{
				errorMsgLst.add(e.getMessage());
				errorMsgPanel.setErrorMessages(errorMsgLst);

			}
		}		
	}//end addOrEditAI

	/**
	 * Method called to Clear all the form fields of the screen
	 */
	public void clear() {
		// TODO Auto-generated method stub

		//set the Field's data to empty values
		editAIDialog.getTxtFldCode().setText("");
		editAIDialog.getAnimalType().addItem("Buffelow");
		editAIDialog.getTxtFldBrthGvn().setText("");
		editAIDialog.getTxtFldBreed().setText("");
		editAIDialog.getTxtFldBullNo().setText("");
		editAIDialog.getTxtFldCattleOWR().setText("");
		editAIDialog.getDtChoDateOfInsemination().setDate(null);
		editAIDialog.getTxtFldAIFee().setText("");
		editAIDialog.getTxtFldKndOfAnml().setText("");
		editAIDialog.getTxtFldMand().setText("");
		editAIDialog.getTxtFldNoAI().setText("");
		editAIDialog.getTxtFldRecpNo().setText("");
		editAIDialog.getTxtFldTOI().setText("");
		editAIDialog.getTxtFldVill().setText("");

		//Method called to set the Field's Labels to default Black color
		clearGUILabelColors(blackColor);

		//ResultPanel
		//	aiDialog.getLblResultOrg().setText("");
		//aiDialog.getLblrRsultCode().setText("");

	}//end clear

	/**
	 * Method called to read the data from GUI and set them to DTO Object 
	 * @param _guiObject
	 */
	@Override
	public void setDtoDetailsToGui(Object object) {
		// TODO Auto-generated method stub
		AIDto _aiDto = (AIDto)object;
		editAIDialog.getTxtFldCode().setText(_aiDto.getCode());
		editAIDialog.getTxtFldAnimalTyp().setText(_aiDto.getAnimalType());
		editAIDialog.getTxtFldBrthGvn().setText(_aiDto.getBirthGiven());
		editAIDialog.getTxtFldBreed().setText(_aiDto.getBreed());
		editAIDialog.getTxtFldBullNo().setText(_aiDto.getBullNo());
		editAIDialog.getTxtFldCattleOWR().setText(_aiDto.getCattleOwner());
		editAIDialog.getTxtFldDOI().setText(DU.format(_aiDto.getDoi(),DBConstants.DISPLAY_DATE_FORMAT));
		editAIDialog.getTxtFldAIFee().setText(_aiDto.getFee());
		editAIDialog.getTxtFldKndOfAnml().setText(_aiDto.getKindOfAnimal());
		editAIDialog.getTxtFldMand().setText(_aiDto.getMandal());
		editAIDialog.getTxtFldNoAI().setText(_aiDto.getNoOfAI());
		editAIDialog.getTxtFldRecpNo().setText(_aiDto.getReceiptNo());
		//aiDialog.getTxtFldTOI().setText(_aiDto.getToi());
		editAIDialog.getTxtFldVill().setText(_aiDto.getVillage());

	}

	/**
	 * Method called to read the data from DTO and set them to GUI.
	 * @param _guiObject
	 */
	@Override
	public void setGuiDetailsToDto(Object object) {
		// TODO Auto-generated method stub
		final EditAIDialog _editAIDialog = (EditAIDialog)object;
		aiDto = new AIDto();
		aiDto.setCode(_editAIDialog.getTxtFldCode().getText());
		aiDto.setAnimalType(_editAIDialog.getAnimalType().getSelectedItem().toString());
		aiDto.setBirthGiven(_editAIDialog.getTxtFldBrthGvn().getText());
		aiDto.setBreed(_editAIDialog.getTxtFldBreed().getText());
		aiDto.setBullNo(_editAIDialog.getTxtFldBullNo().getText());
		aiDto.setCattleOwner(_editAIDialog.getTxtFldCattleOWR().getText());
		//aiDto.setDoi(DU.parse(_aiDialog.getTxtFldDOI().getText()));
		if(_editAIDialog.getDtChoDateOfInsemination().getDate() != null){
			aiDto.setDoi(_editAIDialog.getDtChoDateOfInsemination().getDate());
		}
		aiDto.setFee(_editAIDialog.getTxtFldAIFee().getText());
		aiDto.setKindOfAnimal(_editAIDialog.getTxtFldKndOfAnml().getText());
		aiDto.setMandal(_editAIDialog.getTxtFldMand().getText());
		aiDto.setNoOfAI(_editAIDialog.getTxtFldNoAI().getText());
		aiDto.setReceiptNo(_editAIDialog.getTxtFldRecpNo().getText());
		//aiDto.setToi(_aiDialog.getTxtFldTOI().getText());
		aiDto.getToi().setHour(String.valueOf(_editAIDialog.getVisComBoxModel().getSelectedkey()-1));
		aiDto.getToi().setMinute(String.valueOf(_editAIDialog.getVisComBoxModel2().getSelectedkey()));
		aiDto.getToi().setMeridian(_editAIDialog.getCombxMeridian().getSelectedItem().toString());
		
		aiDto.setVillage(_editAIDialog.getTxtFldVill().getText());
		aiDto.setAiId((Long)_editAIDialog.getHidnObject());

	}


	public void setAICtlr(AICtlr aiCtlr) {
		this.aiCtlr = aiCtlr;
	}

	public AICtlr getAICtlr() {
		return aiCtlr;
	}
	@Override
	public void clearGUILabelColors(Color _lblColor) {
		//set the Field's Labels to default Black color
		editAIDialog.getLblCode().setForeground(_lblColor);
		editAIDialog.getLblAIFee().setForeground(_lblColor);
		editAIDialog.getLblAnimalType().setForeground(_lblColor);
		editAIDialog.getLblBirthsGiven().setForeground(_lblColor);
		editAIDialog.getLblBreed().setForeground(_lblColor);
		editAIDialog.getLblMandal().setForeground(_lblColor);
		editAIDialog.getLblBullNo().setForeground(_lblColor);
		editAIDialog.getLblCattleOwner().setForeground(_lblColor);
		editAIDialog.getLblDOI().setForeground(_lblColor);
		editAIDialog.getLblKindOfAnimal().setForeground(_lblColor);
		editAIDialog.getLblNameOfAI().setForeground(_lblColor);
		editAIDialog.getLblReceiptNo().setForeground(_lblColor);
		editAIDialog.getLblTOI().setForeground(_lblColor);
		editAIDialog.getLblVillage().setForeground(_lblColor);

	}


}
